class User < ActiveRecord::Base
  has_many :users_matches
  has_many :watched_stocks, dependent: :destroy
  has_many :matches, through: :users_matches

  validates :username, :presence => true, :uniqueness => true, :length => { minimum: 5 }
  
  validate :password, :confirmation => true
 
  attr_accessor :password_confirmation

  validate :password_must_be_present

     def User.authenticate(name, password)
          if user = User.find_by(username: name)
               if user.hashed_password == encrypt_password(password, user.salt)
                    user
               end
          end
     end

     def User.encrypt_password(password, salt)
          Digest::SHA2.hexdigest(password + "wobble" + salt)
     end

     # 'password' is a virtual attribute
     def password=(password)
          @password = password

          if password.present?
               generate_salt
               self.hashed_password = self.class.encrypt_password(password, salt)
          end
     end

     def password
     end

     private

     def password_must_be_present
          @errors.add(:password, 'Missing password') unless hashed_password.present?
     end    

     def generate_salt
          self.salt = self.object_id.to_s + rand.to_s
     end

end
